<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="flex-d-row flex-x-bet w-100 ali-item-cen">
				<view class="flex-d-row ali-item-cen fs-28">
					<view :class="noticeType == 0 ? 'col-00ba31 fw-600' : ''" @click="noticeType = 0">系统通知</view>
					<view class="mr-10 ml-10">|</view>
					<view :class="noticeType == 1 ? 'col-00ba31 fw-600' : ''" @click="noticeType = 1">活动通知</view>
				</view>
				<view class="uni-group">
					<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
					<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
					<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
					<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
						@click="delTable">批量删除</button>
					<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
						:type="exportExcel.type" :name="exportExcel.filename">
						<button class="uni-button" type="primary" size="mini">导出 Excel</button>
					</download-excel>
				</view>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace" :orderby="orderby"
				:getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">通知类型</uni-th>
						<uni-th align="center" filter-type="search" v-if="noticeType == 0"
							@filter-change="filterChange($event, 'system_notice_type')" sortable
							@sort-change="sortChange($event, 'system_notice_type')">系统通知类型</uni-th>
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'notice_title')" sortable
							@sort-change="sortChange($event, 'notice_title')">通知标题</uni-th>
						<uni-th v-if="noticeType == 0" align="center" filter-type="search"
							@filter-change="filterChange($event, 'notice_content')" sortable
							@sort-change="sortChange($event, 'notice_content')">通知内容</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'user_id')">发送用户</uni-th>
						<uni-th v-if="noticeType == 0" align="center">接收用户</uni-th>
						<!-- <uni-th align="center">已读状态</uni-th> -->
						<uni-th v-if="noticeType == 1" align="center">关联活动</uni-th>
						<uni-th v-if="noticeType == 1 " align="center">审核</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'notice_time')" sortable
							@sort-change="sortChange($event, 'notice_time')">创建时间</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.notice_type == 0 ? '系统通知' : '活动通知'}}</uni-td>
						<uni-td v-if="noticeType == 0 " align="center">{{item.system_notice_type || '-'}}</uni-td>
						<uni-td align="center">{{item.notice_title || '-'}}</uni-td>
						<uni-td v-if="noticeType == 0" align="center">{{item.notice_content || '-'}}</uni-td>
						<uni-td
							align="center">{{item.user_id && item.user_id[0] && item.user_id[0].text || '-'}}</uni-td>
						<uni-td v-if="noticeType == 0 "
							align="center">{{item.receive_user_id && item.receive_user_id[0] && item.receive_user_id[0].text || '-'}}</uni-td>
						<!-- <uni-td align="center">{{item.user_read_status}}</uni-td> -->
						<uni-td v-if="noticeType == 1 "
							align="center">{{item.activity_id && item.activity_id[0] && item.activity_id[0].text || '-'}}</uni-td>
						<uni-td v-if="noticeType == 1" align="center">
							<view v-if="item.notice_type == 1" class="ping-13-25"
								:class="item.activity_audit_status == 0?'bac-col-4e col-f':item.activity_audit_status==1?'bac-col-00b col-f':'col-87 bac-col-fa'">
								{{item.activity_audit_status == 0 ? '审核中' : item.activity_audit_status == 1 ? '审核通过' : '审核不通过'}}
							</view>
							<view v-else>
								-
							</view>
						</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.notice_time"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button v-if="noticeType == 1 && item.activity_audit_status == 0" class="uni-button"
									size="mini" type="primary" @click="toExamine(item)">审核</button>
								<button
									v-else-if="noticeType == 0 || (noticeType == 1 && item.activity_audit_status != 0)"
									@click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- 审核弹窗 -->
		<view>
			<uni-drawer ref="showRight" mode="right" :width="500">
				<view class="ping-40">
					<view class="w-100 flex-dir-row ali-item-cen bor-bottom-f3 pb-40" style="align-items: stretch;">
						<view class="shu"></view>
						<view class="fs-32 fw-900 ml-10">通知审核</view>
					</view>
					<view class="pt-40">
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">审核状态：</view>
							<view class="fs-30 ping-15-80"
								:class="examineData.activity_audit_status == 0?'bac-col-4e col-f':examineData.activity_audit_status==1?'bac-col-00b col-f':'col-87 bac-col-fa'">
								{{examineData.activity_audit_status == 0 ? '审核中' : examineData.activity_audit_status == 1 ? '审核通过' : '审核不通过'}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen  mb-40">
							<view class="fs-30 fw-600">通知标题：</view>
							<view class="fs-30">
								{{examineData.notice_title}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen  mb-40">
							<view class="fs-30 fw-600">通知内容：</view>
							<view class="fs-30">
								<rich-text :nodes="examineData.notice_content"></rich-text>
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">发送用户：</view>
							<view class="fs-30">
								{{examineData.user_id && examineData.user_id.length?examineData.user_id[0].text: '-'}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">接收用户：</view>
							<view class="fs-30">
								{{examineData.receive_user_id && examineData.receive_user_id.length?examineData.receive_user_id[0].text: '所有报名此活动的用户'}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">关联活动：</view>
							<view class="fs-30">
								{{examineData.activity_id && examineData.activity_id.length?examineData.activity_id[0].text: '-'}}
							</view>
						</view>

					</view>
					<!-- 审核按钮 -->
					<view v-if="examineData.activity_audit_status == 0"
						class="flex-dir-row ali-item-cen flex-x-spa mt-40">
						<button style="width: 300rpx;height: 80rpx;line-height: 80rpx;" type="primary" size="mini"
							@click="examine(1)">通过审核</button>
						<button style="width: 300rpx;height: 80rpx;line-height: 80rpx;" type="warn" size="mini"
							@click="examine(2)">拒绝通过</button>
					</view>
				</view>
			</uni-drawer>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/qmy-notice.js';

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'notice_time desc' // 排序字段
	const dbSearchFields = ['notice_title',
		'notice_content'
	] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				collectionList: [db.collection('qmy-notice').field(
						'notice_type,system_notice_type,notice_title,notice_content,user_id,receive_user_id,user_read_status_array,user_read_status,activity_id,activity_audit_status,notice_time'
					).getTemp(), db.collection('uni-id-users').field('nickname as text, _id').getTemp(), db
					.collection('qmy-activity').field('name as text, _id').getTemp()
				],
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "qmy-notice.xls",
					"type": "xls",
					"fields": {
						"notice_type": "notice_type",
						"通知标题": "notice_title",
						"通知内容": "notice_content",
						"发送用户": "user_id",
						"接收用户": "receive_user_id",
						"已读用户": "user_read_status_array",
						"已读状态": "user_read_status",
						"关联活动": "activity_id",
						"审核": "activity_audit_status",
						"创建时间": "notice_time"
					}
				},
				exportExcelData: [],
				noticeType: 0,
				examineData: {}
			}
		},
		watch: {
			noticeType(newVal) {
				this.where = `notice_type == ${newVal}`
				this.$nextTick(() => {
					this.loadData()
				})
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			toExamine(data) {
				this.examineData = data
				this.$refs.showRight.open()
			},
			examine(status) {
				// 修改通知审核状态
				db.collection('qmy-notice').doc(this.examineData._id).update({
					activity_audit_status: status
				}).then(res => {
					uni.showToast({
						title: '审核成功',
						icon: 'none'
					})
					setTimeout(() => {
						this.$refs.showRight.close()
						this.loadData()
					}, 1000)
				}).catch(err => {
					uni.showToast({
						title: '审核失败，' + err.message,
						icon: 'none'
					})
				})
			},
			onqueryload(data) {
				this.exportExcelData = data
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style>
</style>